import { message, Modal as AModal, Form, Input, Select } from 'antd'
import { updateBookApi } from '@/api/books'
import type { UpdateBookInterface, AddBookInterface } from '@/types/api'

const { TextArea } = Input

interface DataInterface {
  [key: string]: string
}

function Modal(props: {
  isModalOpen: boolean
  setIsModalOpen: React.Dispatch<React.SetStateAction<boolean>>
  books: DataInterface
  cb: (data: DataInterface) => void
  status?: string
}) {
  const { isModalOpen, setIsModalOpen, books, cb, status = 'update' } = props
  // 初始化表单数据
  const [form] = Form.useForm()

  const handleOk = async () => {
    const formData = form.getFieldsValue()

    const params = {
      //   book_id: books?.id,
      book_url: formData?.url,
      book_name: formData?.name,
      book_desc: formData?.description,
      status: formData?.book_status === '公开' ? 1 : 0,
      books_id: books?.parent_id
    }

    if (status === 'update') {
      params['book_id'] = books?.id
      await update(params as UpdateBookInterface)
    } else {
      await add(params as AddBookInterface)
    }
    handleCancel()
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }

  const update = async (params: UpdateBookInterface) => {
    const { code, data, msg } = await updateBookApi(params)
    if (code !== 200) return message.error(msg)
    message.success('修改成功')
    cb(data)
    return data
  }

  const add = async (params: AddBookInterface) => {}

  return (
    <AModal
      open={isModalOpen}
      onOk={handleOk}
      onCancel={handleCancel}
      zIndex={2001}
      cancelText="取消"
      closable={false}
      okText="确定"
    >
      <br />
      <Form
        form={form}
        initialValues={
          books && { ...books, book_status: books?.status === 'public' ? '公开' : '私密' }
        }
      >
        <Form.Item
          label="书签名字"
          name="name"
          rules={[{ required: true, message: '请输入书签名字' }]}
        >
          <Input placeholder="请输入书签名字" />
        </Form.Item>

        <Form.Item
          label="书签地址"
          name="url"
          rules={[{ required: true, message: '请输入书签地址' }]}
        >
          <Input placeholder="请输入书签地址" />
        </Form.Item>

        <Form.Item
          label="书签状态"
          name="book_status"
          rules={[{ required: true, message: '请输入书签状态' }]}
        >
          <Select
            placeholder="书签可见性"
            style={{ zIndex: 2002, width: '100%' }}
            options={[
              { value: '1', label: '公开' },
              { value: '0', label: '私密' }
            ]}
          />
        </Form.Item>

        <Form.Item
          label="书签描述"
          name="description"
          rules={[{ required: true, message: '请输入书签描述' }]}
        >
          <TextArea placeholder="请输入书签备注" autoSize={{ minRows: 2, maxRows: 6 }} />
        </Form.Item>
      </Form>
    </AModal>
  )
}

export default Modal
